package it.canraid.leaflet.control.activity;

import it.canraid.leaflet.control.Kernel;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;

public class BackgroundService extends Service {
    private static TimerThread timerThread = null;

    public IBinder onBind(Intent arg0) {
	return null;
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
	boolean shouldCreate = false;
	long deltaTime = Kernel.DELTA_TIME_SHUTDOWN_SERVICE;
	if (intent != null) {
	    Bundle bundle = intent.getExtras();
	    if (bundle != null) {
		long aux = bundle.getLong(Kernel.LABEL_DELTA_TIME_SHUTDOWN_SERVICE);
		if (aux != 0L) {
		    deltaTime = aux;
		}
	    }
	}

	if (timerThread == null)
	    shouldCreate = true;
	else if (!timerThread.isRunning())
	    shouldCreate = true;

	if (shouldCreate) {
	    timerThread = new TimerThread(deltaTime);
	} else {
	    timerThread.automaticShutDown(deltaTime);
	}
	return START_REDELIVER_INTENT;
    }

    public void onDestroy() {
	if (timerThread != null)
	    timerThread.forceShutDown();

	timerThread = null;
	super.onDestroy();
    }

    private class TimerThread extends Thread {
	private Long timeToDie;
	private volatile boolean requestToStop = false;
	private volatile boolean run = false;

	public TimerThread(long deltaTime) {
	    super("TIMER_SERVICE_BACKGROUND:" + TimerThread.class.getName());
	    automaticShutDown(deltaTime);
	}

	public boolean isRunning() {
	    return run;
	}

	public void automaticShutDown(long deltaTime) {
	    synchronized (timeToDie) {
		timeToDie = System.currentTimeMillis() + deltaTime;
	    }
	}

	public void forceShutDown() {
	    requestToStop = true;
	}

	public void run() {
	    run = true;
	    try {
		long auxTimeToDie = 0;
		do {
		    sleep(1000);
		    synchronized (timeToDie) {
			auxTimeToDie = timeToDie;
		    }
		} while (System.currentTimeMillis() < auxTimeToDie && !requestToStop);
	    } catch (InterruptedException e) {
	    }
	    stopSelf();
	    run = false;
	}
    }

}